/*
 * ADC.c
 *
 *  Created on: 09-02-2012
 *      Author: Mati
 */

#include "ADC.h"
//extern volatile uint16_t AD_last;
//extern xQueueHandle xAdc2UartQueue;

/*------------------------------------------------------------------------------
  configer ADC
 *------------------------------------------------------------------------------*/
__INLINE void ADC_Config(void) {
	LPC_PINCON->PINSEL3 |= (3U<<30);	//AD0.5 -> 0b11 na P1.31

	LPC_SC->PCONP |= (1U<<12);		/* turn ON ADC*/
	LPC_ADC->ADCR  = (1U<<5) |     	/* select AD0.5 pin - potentiometer   */
	                 (1U<<8) |     	/* ADC clock is 25MHz/(1+1)               */
	                 (1U<<21);//|      /* enable ADC   - PDN_bit             */
					 //(6U<<24);		/* start conversion when MAT1.0 on */
	LPC_ADC->ADCR |= (1<<16);     	//burst

	uint8_t trim = 2;
	LPC_ADC->ADTRM&=~0x00F0;
	LPC_ADC->ADTRM|=(trim<<4) & 0x00F0;   //set the trim

	//NVIC_EnableIRQ(ADC_IRQn);       /* enable ADC Interrupt               */
	//LPC_ADC->ADINTEN |= (1<<5);	//|(1<<8)) 5th channel will generate an interrupt + global interrupts
}

/*------------------------------------------------------------------------------
  ADC Handler
 *------------------------------------------------------------------------------*/

/*void ADC_IRQHandler(void){

}*/

float AverageValue(uint32_t *table)
{
	uint32_t *initPtr = table;
	uint16_t num = NUM_OF_ADC_SAMPLES;
	uint32_t idx = 0;
	uint32_t sum = 0;
	uint32_t value = 0;
	float avg_1st_step = 0;
	uint32_t minRange = 0;
	uint32_t maxRange = 0;

	while(num--)
	{
		value = *initPtr++;
		value &= 0xFFF0;
		idx++;
		sum += (uint32_t)value;
	}

	avg_1st_step = (float)((float)sum/(float)idx);
	num = NUM_OF_ADC_SAMPLES;
	idx = 0;
	sum = 0;
	value = 0;
	maxRange = (uint32_t)(avg_1st_step+(avg_1st_step*0.15));
	minRange = (uint32_t)(avg_1st_step-(avg_1st_step*0.15));

	while(num--)
	{
		value = *table++;
		value &= 0xFFF0;
		if( (value > maxRange) || (value < minRange) )
			continue;
		value = value>>4;
		idx++;
		sum += (uint32_t)value;
	}

	return (float)((float)sum/(float)idx);
}

/*uint32_t min(uint32_t *tab)
{
	uint8_t size = FILTER_SIZE;
	uint32_t val;
	uint32_t minVal = ~0;
	while(size--)
	{
		val = tab[size-1];
		if(val < minVal)
			minVal = val;
	}
	return minVal;
}

uint32_t max(uint32_t *tab)
{
	uint8_t size = FILTER_SIZE;
	uint32_t val;
	uint32_t maxVal = 0;
	while(size--)
	{
		val = tab[size-1];
		if(val > maxVal)
			maxVal = val;
	}
	return maxVal;
}*/
